"use client";

import { Button, message } from "antd";
import { useEffect, useState } from "react";
import { listMultiVoByPageUsingPost } from "@/api/mutliQuestionController";
import { useSelector } from "react-redux";
import { RootState } from "@/stores";
import { useRouter } from "next/navigation";

interface ExamButtonProps {
  questionBankId: number;
}

export default function ExamButton({ questionBankId }: ExamButtonProps) {
  const [hasOnlineQuestions, setHasOnlineQuestions] = useState(false);
  const [loading, setLoading] = useState(true);
  const loginUser = useSelector((state: RootState) => state.loginUser);
  const router = useRouter();

  useEffect(() => {
    const checkOnlineQuestions = async () => {
      try {
        const res = await listMultiVoByPageUsingPost({
          questionBankId: questionBankId,
          pageSize: 1,
          current: 1,
        });
        // @ts-ignore
        setHasOnlineQuestions(res.data?.total > 0);
      } catch (e) {
        console.error(" ：", e);
      } finally {
        setLoading(false);
      }
    };

    checkOnlineQuestions();
  }, [questionBankId]);

  const handleClick = () => {
    if (!loginUser.id) {
      message.warning("请先登录");
      router.push("/user/login");
      return;
    }
    router.push(`/exam/${questionBankId}`);
  };

  return (
    <Button
      type="default"
      shape="round"
      onClick={handleClick}
      style={{ marginLeft: 15 }}
      disabled={loading || !hasOnlineQuestions}
    >
      在线测试
    </Button>
  );
}
